import { fetch, post, cascade } from 'plugins/axios'
import { Dialog, QSpinnerGears } from 'quasar'

export function loadHeaders ({state, commit}) {
  return new Promise((resolve, reject) => {
    fetch('/getmodels/', {
      appname: 'publisher',
      modelname: 'publisher'
    }).then((response) => {
      commit('headerSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function loadTable ({state, commit}, payload) {
  return new Promise((resolve, reject) => {
    state.loading = true
    const {sortBy, descending, page, rowsPerPage} = state.serverPagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/publisher/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search,
      Project: payload
    }).then((response) => {
      commit('loadTableSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function doPublish ({state, dispatch, commit}, payload) {
  post('/publisher/do_roll_publish/', {
    opt: payload
  }).then((response) => {
    alert(response)
    state.verifyDialog = false
    dispatch('loadTable', this.$router.history.current.params.projectId)
  }).catch((error) => {
    alert(error.response.data.error)
  })
}

export function doGrayPublish ({state, dispatch, commit}, payload) {
  let array = []
  array.push(payload)
  post('/publisher/do_gray_publish/',
    array
  ).then((response) => {
    alert(response.data)
    state.grayDialog = false
    dispatch('loadTable', this.$router.history.current.params.projectId)
  }).catch((error) => {
    alert(error.response.data.error)
  })
}

export function deletePublish ({state, dispatch, commit}, payload) {
  Dialog.create({
    title: '删除发布',
    message: '确定删除发布？',
    ok: '提交',
    cancel: '再想想'
  }).then(() => {
    state.loadPage.show({spinner: QSpinnerGears})
    let url = '/publisher/' + payload + '/'
    cascade(url, {}).then((response) => {
      state.loadPage.hide()
      dispatch('loadTable', this.$router.history.current.params.projectId)
    }).catch((error) => {
      alert(error.response.data)
      state.loadPage.hide()
    })
  }).catch(() => {
    console.log('stay')
  })
}

export function getFileReplace ({state, commit}, payload) {
  fetch('/publisher/get_file_replace/', {
    Project: payload
  }).then((response) => {
    state.fileButton = JSON.parse(response).data
  }).catch((error) => {
    state.etext = error.response
  })
}

export function grayContinue ({state, dispatch, commit}, payload) {
  Dialog.create({
    title: '灰度确认',
    message: '确定灰度验证通过？',
    ok: '提交',
    cancel: '再想想'
  }).then(() => {
    dispatch('doGrayPublish', payload)
  }).catch(() => {
    console.log('stay')
  })
}
